package com.ken.astroboy.thread;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.web.socket.TextMessage;

import com.google.gson.Gson;
import com.ken.astroboy.core.InMemoryStorage;
import com.ken.astroboy.listener.WechatListener;
import com.ken.astroboy.logic.LogicProcess;
import com.ken.astroboy.service.WxService;
import com.ken.astroboy.util.Exceptions;
import com.ken.astroboy.websocket.SpringWebSocketHandler;

public class InitRobotThread implements Runnable{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Bean//这个注解会从Spring容器拿出Bean
    public SpringWebSocketHandler wsHandler() {
        return new SpringWebSocketHandler();
    }

    @Override
    public void run() {
        
        logger.info("Enter InitRobotThread");
        
        Map<String, String> map = new HashMap<>();                       
        Gson gson = new Gson();
        boolean isQrCodeScanned = false;
        boolean isLoginOK = false;
     
        try {
            String tip = "1";// 首次时为1
            long currentTimeMillis = System.currentTimeMillis();// 首次时为系统时间，之后每次请求加1

            while(true){
                
                String code = WxService.checkLoginStatus(tip, currentTimeMillis++);
                tip = "0";
                           
                if (code != null) {    
                    
                    map.put("code", code);
                    
                    if (code.equals("201")) {
                         
                        if(!isQrCodeScanned){
                            
                            map.put("avatar", WxService.getAvatarUrl());
                            map.put("msg", "扫描成功,请在手机上点击确认登录");
                            wsHandler().sendMessageToUser("default-system", new TextMessage(gson.toJson(map)));
        
                            isQrCodeScanned = true;                        
                        }
                        
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        
                    } else if (code.equals("200")) {
                        map.put("msg", "手机已经点击确认登录");
                        wsHandler().sendMessageToUser("default-system", new TextMessage(gson.toJson(map)));                  
                        isLoginOK = true;
                        break;
                        
                    } else if (code.equals("408")) {
                        map.put("msg", "登录超时，请重新登录");
                        wsHandler().sendMessageToUser("default-system", new TextMessage(gson.toJson(map)));
                        break;
                        
                    }
                }            
            }

            LogicProcess.closeQrWindow();

            if(isLoginOK){

                LogicProcess.start();                                       

                if(LogicProcess.loadQuartzAndStartScheduler()){
                    if(!LogicProcess.pauseJobsDueToConfig()){
                        
                        logger.info("暂停定时任务失败，请重新尝试登陆");
                        map.put("msg", "暂停定时任务失败，请重新尝试登陆");
                        map.put("code", "901");
                        LogicProcess.initDataInWxServiceAndInMemoryStorage();
                        wsHandler().sendMessageToUser("default-system", new TextMessage(gson.toJson(map)));
                        
                        return;
                    }                               
                }else{
                    logger.info("启动定时任务失败，请重新尝试登陆");
                    map.put("msg", "启动定时任务失败，请重新尝试登陆");
                    map.put("code", "902");
                    LogicProcess.initDataInWxServiceAndInMemoryStorage();
                    wsHandler().sendMessageToUser("default-system", new TextMessage(gson.toJson(map)));

                    return;
                }
               
                //一切正常，开启消息监听线程
                WechatListener wechatListener = new WechatListener("消息监听");
                wechatListener.start();
            } 
        }catch(Exception e) {
        	
        	logger.info("InitRobotThread 异常");
        	logger.info(Exceptions.getExceptionDetail(e));
        	InMemoryStorage.isRobotInitializing = false;
        	
        }
        
        InMemoryStorage.isRobotInitializing = false;
    }

}
